import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { ReportUrls } from 'app/ptpmc/comm/report.urls.conf';
import { CommService } from 'app/ptpmc/comm/comm.service';
import * as Enumerable from 'linq';
import { CurrentProdStat } from 'app/ptpmc/model/report/monitor';
import { GlobalDataManager } from 'app/ptpmc/comm/global-data-manager';
import { QueryModel } from 'app/ptpmc/model/report/query-model';
import { WebSocketService } from 'app/ptpmc/comm/websocket-service';
import { LocalStorage } from 'app/ptpmc/localstorage/local.storage';
import { Router, NavigationEnd } from '@angular/router';
import { Project } from 'app/ptpmc/model/comm/config-data';
declare var h5_android;
@Component({
    selector: 'app-home-v3',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.scss'],
    providers: [WebSocketService]
})
export class HomeComponent implements OnInit, OnDestroy {

    loginNum = 0;

    prodCountChartOption: any = {};
    stChartOption: any = {};
    btChartOption: any = {};
    ctChartOption: any = {};
    dtChartOption: any = {};
    prodList: any[] = [];
    lastCt: any[] = [];
    lastD: any[] = [];
    assistList: any[] = [];
    alarmList: any[] = [];
    loading = true;
    dateTime = new Date();
    subAreaSelected = null;
    target = 0;
    completed = '100';
    currentWorkDay = '';
    currentShift = 1;
    chartsMap = new Map<number, any>();
    timer: any;
    countTimer: any;
    alarmTimer: any;
    audioTimer: any;
    public projectItems: Project[] = [];
    projectSelected = null;

    audioList = [];
    currentAudio;

    curUserId;

    /** 用于计时 切换区域*/
    timerNum = 0;

    height;

    workStatus = '';
    isToggle = true;
    toggleLable = '播放';

    loadData = true;

    target1 = 0;
    target2 = 0;
    onLine1 = 0;
    offLine1 = 0;
    completed1 = '100';
    subAreaItems = [];

    constructor(public router: Router,
        private commServices: CommService, private wsService: WebSocketService, private ls: LocalStorage, ) { }

    toggle() {
        this.isToggle = !this.isToggle;
        if (this.isToggle) {
            this.toggleLable = '播放';
        } else {
            this.toggleLable = '暂停';
        }
    }


    ngOnInit() {
        this.height = window.innerHeight;
        this.loading = true;
        this.loading = false;
        this.dateTime = new Date();
        this.curUserId = this.ls.get('ptpmc_userId');
        // subscribe shop change
        this.commServices.emitterShop.subscribe(shop => {
            debugger
            if (shop !== this.projectSelected) {
                this.projectSelected = GlobalDataManager.getProjectSelected().projectName;
                console.log(`车间变换....${shop}`)
                this.clearMonitorData()
                this.subAreaItems = [];
                this.subAreaSelected = undefined;
                this.connWs()
            }
        })
        this.commServices.emitter.subscribe(data => {
            this.subAreaItems = data;
            console.log(`区域变换....${JSON.stringify(this.subAreaItems)}`)
            this.permissionSubArea();
        })

        this.listenerRouter();

        this.startRefreshMonitorData();
    }

    get canLoadData(){
        const canInterval = this.loadData && this.workStatus == 'Line In Production' 
        && this.subAreaSelected && this.projectSelected === GlobalDataManager.getProjectSelected().projectName
        return canInterval;
    }

    startRefreshMonitorData(){
        // 获取产量实时监控 30秒钟一次
        this.countTimer = setInterval(() => {
            if (this.canLoadData) {
                console.log('时间到啦...刷新产量数据')
                this.getProdData();
            }
        }, 30000);

        // 获取报警实时监控 5 秒钟一次
        this.alarmTimer = setInterval(() => {
            if (this.canLoadData) {
                console.log('时间到啦...刷新其他数据')
                this.getAssistData();
                this.getAlarmData();
                this.getLastctData();   // CT数据
                this.getReportData();   // 停机数据

                if (this.audioList && this.audioList.length > 0) {
                    const brower = navigator.userAgent;
                    this.currentAudio = this.audioList.shift();
                    if (brower.indexOf('Android') !== -1) {
                        h5_android.playMp3(this.currentAudio.value);
                    } else {
                        const a = document.createElement('audio');
                        a.src = this.currentAudio.value;
                        a.play();
                    }
                    if (this.currentAudio.subArea && this.currentAudio.subArea !== '') {
                        this.toTab(this.currentAudio.subArea);
                    }
                }
                this.timerNum += 5;
                if (this.timerNum >= 20) {
                    this.toNextTab();
                }
            }
        }, 20000);
    }

    permissionSubArea () {
        this.commServices.doGet(`${ReportUrls.AllSubArea}/${this.curUserId}`).subscribe(model => {
            if (model.resultCode === 200 && model.data) {
                const areas = model.data[0].subArea;
                const tmpItems = [];
                if (areas && areas.length > 0 && this.subAreaItems && this.subAreaItems.length > 0) {
                    const subAreaPermission = areas.split(',');
                    subAreaPermission.forEach(element => {
                        const data = this.subAreaItems.find(item => item.subArea === element);
                        if (data) {
                            tmpItems.push(data);
                        }
                    });
                    if (tmpItems.length > 0) {
                        this.subAreaItems = tmpItems;
                    }
                }
                if (this.subAreaItems.length > 0) {
                    this.subAreaSelected = this.subAreaItems[0];
                    this.initDatas();
                }
            } else {
                this.subAreaSelected = this.subAreaItems[0];
                this.initDatas();
            }
        });
    }

    listenerRouter() {
        // 路由事件
        this.router.events
            .filter(event => event instanceof NavigationEnd)
            .subscribe((event: any) => {
                 if (event.url === '/ptpmc/home') {
                    this.loadData = true;
                } else {
                    this.loadData = false;
                }
            });
    }

    initDatas() {
        console.log(`开始获取产线${this.subAreaSelected.subArea}的数据.....`)
        this.commServices.doGet(`/sh/filter/currentStatus/${this.subAreaSelected.subArea}`).subscribe(res => {
            if (res.resultCode === 200) {
                
                if (res.data) {
                    this.workStatus = 'Line In Production';
                    this.getProdData();     // 产量数据
                    this.getAssistData();   // 求助数据
                    this.getAlarmData();    // 报警数据
                    this.getLastctData();   // CT数据
                    this.getReportData();   // 停机数据
                    
                } else {
                    this.workStatus = 'Not In Production';
                    this.clearMonitorData();
                }
            } else {
                this.workStatus = 'Not In Production';
                this.clearMonitorData();
            }
        });
    }

    toTab(subArea) {
        if (this.isToggle) {
            this.timerNum = 0;
            if (typeof (subArea) === 'string') {
                const find = this.subAreaItems.find(e => e.subArea === subArea);
                this.subAreaChange(find);
            } else {
                this.subAreaChange(subArea);
            }
        }
    }

    subAreaChange(subArea: any) {
        this.timerNum = 0;
        this.subAreaSelected = subArea;
        this.clearMonitorData();
        this.initDatas()
    }

    toNextTab() {
        if (this.subAreaItems && this.subAreaItems.length > 0) {
            let index = this.subAreaItems.findIndex(e => e.subArea === this.subAreaSelected.subArea);
            if (index === this.subAreaItems.length - 1) {
                index = 0;
            } else {
                index += 1;
            }
            this.toTab(this.subAreaItems[index]);
        }
    }

    connWs() {
        try {
            if (this.wsService && this.wsService.ws) { this.wsService.ws.close(); }
        } catch (e) {

        }
        const url = ReportUrls.BaseUrl.replace('http://', '');
        this.wsService.createObservableSocket(`ws://${url}/ws?uid=${this.ls.get('ptpmc_userId')}`)
            .subscribe(
                data => {
                    try {
                        const res = JSON.parse(data);
                        if (res.key === 'exit') {
                            // alert('当前账户在其它电脑登录！');
                        } else if (res.key === 'play_wav') {
                            // const wavUrl = ReportUrls.BaseUrl + res.value;
                            // res.value = wavUrl;
                            // this.audioList.push(res);
                        } else if (res.key === 'login_num') {
                            this.loginNum = res.value;
                        }
                    } catch (e) {

                    }
                },
                err => { console.log(err); },
                () => { console.log('流已经结束'); this.audioList = []; }
            );
    }

    ngOnDestroy(): void {
        clearInterval(this.countTimer);
        clearInterval(this.alarmTimer);
    }

    clearMonitorData () {
        this.workStatus = 'Not In Production';
        this.target1 = 0;
        this.target2 = 0;
        this.onLine1 = 0;
        this.offLine1 = 0;
        this.completed1 = '-';
        this.assistList = [];
        this.alarmList = [];
        this.prodCountChartOption = {};
        //this.ctChartOption = {};
        //this.dtChartOption = {};
        this.stChartOption = {};
        this.btChartOption = {};
    }

    private getProdData() {
        this.commServices.doGet(`/mon/prod/info/${this.subAreaSelected.subArea}`)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    this.target1 = model.data.all;
                    this.target2 = model.data.gd;
                    
                    
                    if (this.subAreaSelected.subArea !== 'LGAL2') {
                        this.onLine1 = model.data.loadOp;
                    }
                    if (this.subAreaSelected.subArea !== 'LGAL1') {
                        this.offLine1 = model.data.unLoadOp;
                    }

                    this.completed1 = ((this.offLine1 / this.target1) * 100).toFixed(2);
                }
        });
        this.commServices
            .getList(null, ReportUrls.MonProdUrl)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    this.prodList = model.data;
                    this.showPordCountChart();
                } else {
                }
            });
    }


    private getAssistData() {
        this.commServices
            .getList(null, ReportUrls.MonAssistUrl)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    const tempData: any[] = model.data;
                    if (tempData) {
                        this.assistList = Enumerable.from(tempData).where(u => u.subArea === this.subAreaSelected.subArea).toArray();
                        this.assistList.map(e => e.equipment = e.equipment.replace(new RegExp('_', 'gm'), ''));
                    } else {
                        this.assistList = [];
                    }
                } else {
                    this.assistList = [];
                }
            });
    }

    private getAlarmData() {
        this.commServices
            .getList(null, ReportUrls.MonAlarmUrl)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    const tempData: any[] = model.data;
                    if (tempData) {
                        this.alarmList = Enumerable.from(tempData).where(u => u.subArea === this.subAreaSelected.subArea).toArray();
                        this.alarmList.map(e => e.equipment = e.equipment.replace(new RegExp('_', 'gm'), ''));
                    } else {
                        this.alarmList = [];
                    }
                } else {
                    this.alarmList = [];
                }
            });
    }
    /**ECharts图表相关*/
    onChartInit(index: number, echartsIntance: any): void {
        this.chartsMap.set(index, echartsIntance);
        // Observable.fromEvent(window, 'resize')
        //     .debounceTime(100) // 以免频繁处理
        //     .subscribe((event) => this.chartsMap.forEach((v, k) => v.resize()));
    }

    private showPordCountChart(): void {
        let currentProdList = [];
        let topList = [];
        const targetData = [];
        const actData = [];
        let currentStList = [];
        let currentBtList = [];
        const btCategory = [];
        const stCategory = [];
        const btData = [];
        const stData = [];
        this.target = 0;
        this.completed = '-';
        try {
            if (this.prodList !== undefined && this.prodList.length > 0) {
                currentProdList = Enumerable.from(this.prodList).where(u => u.subArea === this.subAreaSelected.subArea)
                    .orderBy(u => u.hours).toArray();
                // currentWorkDay
                this.currentWorkDay = Enumerable.from(currentProdList).first().shiftDay;
                // currentShift
                this.currentShift = Enumerable.from(currentProdList).first().shiftId;
                // 小时产量,选出区域中下线工位得小时分组求和
                const loadHoursData = Enumerable.from(currentProdList).where(u => u.loadOP === 1).groupBy(u => u.hours).select(u => {
                    const temp: CurrentProdStat = new CurrentProdStat();
                    temp.jph = u.first().jph;
                    temp.hours = u.first().hours;
                    temp.gd = u.sum(item => item.gd);
                    return temp;
                }).orderBy(u => u.hours).toArray();
                const unLoadHoursData = Enumerable.from(currentProdList).where(u => u.unloadOP === 1).groupBy(u => u.hours).select(u => {
                    const temp: CurrentProdStat = new CurrentProdStat();
                    temp.jph = u.first().jph;
                    temp.hours = u.first().hours;
                    temp.gd = u.sum(item => item.gd);
                    return temp;
                }).orderBy(u => u.hours).toArray();
                let preGd = 0;
                unLoadHoursData.forEach((item) => {
                    actData.push(item.gd - preGd);
                    targetData.push(item.jph);
                    preGd = item.gd;
                });
                // 上线产量
                // if (loadHoursData.length > 0) {
                //     this.onLine = Enumerable.from(loadHoursData).max(u => u.gd);
                // }
                if (this.subAreaSelected.subArea === 'LGAL2') {
                    this.onLine1 = this.getUnLoadProd('LGAL1', 1);
                }
                // 下线产量
                // if (unLoadHoursData.length > 0) {
                //     this.offLine = Enumerable.from(unLoadHoursData).max(u => u.gd);
                // }
                if (this.subAreaSelected.subArea === 'LGAL1') {
                    this.offLine1 = this.getUnLoadProd('LGAL2', 2);
                    this.completed1 = ((this.offLine1 / this.target1) * 100).toFixed(2);
                }

                // 目标产量
                switch (this.currentShift) {
                    case 1:
                        this.target = Enumerable.from(currentProdList).first().target1;
                        break;
                    case 2:
                        this.target = Enumerable.from(currentProdList).first().target2;
                        break;
                    case 3:
                        this.target = Enumerable.from(currentProdList).first().target3;
                        break;
                }
                // 产量完成率
                // this.completed = ((this.offLine / this.target) * 100).toFixed(2);
                topList = Enumerable.from(currentProdList).groupBy(u => u.equipment).select(items => {
                    let temp = new CurrentProdStat();
                    temp = items.first();
                    temp.bt = (items.sum(item => item.bt) / 600).toFixed(2);
                    temp.st = (items.sum(item => item.st) / 600).toFixed(2);
                    return temp;
                }).toArray();
                currentBtList = Enumerable.from(topList).orderByDescending(u => Number.parseFloat(u.bt)).take(5).toArray();
                currentStList = Enumerable.from(topList).orderByDescending(u => Number.parseFloat(u.st)).take(5).toArray();

                currentBtList.forEach((item) => {
                    btCategory.push(item.equipment.replace(new RegExp('_', 'gm'), ''));
                    btData.push(item.bt);
                });
                currentStList.forEach((item) => {
                    stCategory.push(item.equipment.replace(new RegExp('_', 'gm'), ''));
                    stData.push(item.st);
                });
                this.prodCountChartOption = this.getHourOptions(targetData, actData); // 产量图
                this.stChartOption = this.getTopOptions('堵料', '#E87C25', btCategory, btData);
                this.btChartOption = this.getTopOptions('待料', '#FE8463', stCategory, stData);
            } else {
                this.prodCountChartOption = {};
                this.stChartOption = {};
                this.btChartOption = {};
            }
        } catch (e) {
            this.prodCountChartOption = {};
            this.stChartOption = {};
            this.btChartOption = {};
        }


    }

    // 首页CT柱状图数据
    private getLastctData() {
        const queryModel: QueryModel = new QueryModel();
        queryModel.dateTimeRange = this.currentWorkDay;
        queryModel.querySubAreaIds = [this.subAreaSelected.subArea];
        queryModel.shift = this.currentShift;
        this.commServices
            .getList(queryModel, ReportUrls.CTListUrlCt)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    this.lastCt = model.data;
                    const ctCategory = [];
                    const ctData = [];
                    if (this.lastCt && this.lastCt.length > 0) {
                        this.lastCt.forEach(u => {
                            const equipment = u.equipment;
                            ctCategory.push(equipment.replace(new RegExp('_', 'gm'), ''));
                            ctData.push(u.lastCt);
                        });
                        if (ctData.length === 0) {
                            this.ctChartOption = {};
                        } else {
                            this.ctChartOption = this.getTopOptions('CT', '#C1232B', ctCategory, ctData);
                        }
                    } else {
                        this.ctChartOption = {};
                    }
                } else {
                    this.ctChartOption = {};
                }
            });
    }

    // 首页停机柱状图数据
    getReportData(): void {
        const queryModel: QueryModel = new QueryModel();
        queryModel.dateTimeRange = this.currentWorkDay;
        queryModel.querySubAreaIds = [this.subAreaSelected.subArea];
        queryModel.shift = this.currentShift;
        this.commServices
            .getList(queryModel, ReportUrls.TipFaultT)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    this.lastD = model.data;
                    const dtCategory = [];
                    const dtData = [];
                    if (this.lastD && this.lastD.length > 0) {
                        this.lastD.forEach(u => {
                            const station = u.station;
                            dtCategory.push(station.replace(new RegExp('_', 'gm'), ''));
                            dtData.push(u.duration);
                        });
                        if (dtData.length === 0) {
                            this.dtChartOption = {};
                        } else {
                            this.dtChartOption = this.getTopOptions('停机', '#FF4500', dtCategory, dtData);
                        }
                    } else {
                        this.dtChartOption = {};
                    }
                } else {
                    this.dtChartOption = {};
                }
            });
    }


    private getUnLoadProd(subArea, type) {
        const prod = Enumerable.from(this.prodList).where((u: any) => u.subArea === subArea)
            .orderBy((u: any) => u.hours).toArray();
        let unLoadHoursData;
        if (type === 1) {
            unLoadHoursData = Enumerable.from(prod).where((u: any) => u.loadOP === 1)
                .groupBy((u: any) => u.hours).select((u: any) => {
                    const temp: CurrentProdStat = new CurrentProdStat();
                    temp.jph = u.first().jph;
                    temp.hours = u.first().hours;
                    temp.gd = u.sum(item => item.gd);
                    return temp;
                }).orderBy(u => u.hours).toArray();
        } else {
            unLoadHoursData = Enumerable.from(prod).where((u: any) => u.unloadOP === 1)
                .groupBy((u: any) => u.hours).select((u: any) => {
                    const temp: CurrentProdStat = new CurrentProdStat();
                    temp.jph = u.first().jph;
                    temp.hours = u.first().hours;
                    temp.gd = u.sum(item => item.gd);
                    return temp;
                }).orderBy(u => u.hours).toArray();
        }
        // 下线产量
        const offLine = Enumerable.from(unLoadHoursData).max((u: any) => u.gd);
        return offLine;
    }

    private getHourOptions(targetData: Array<any>, actData: Array<any>): any {
        const option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                    type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                }
            },
            xAxis: {
                type: 'category',
                data: ['1H', '2H', '3H', '4H', '5H', '6H', '7H', '8H', '9H', '10H', '11H']
            },
            yAxis: {
                type: 'value'
            },
            grid: {
                top: '5px',
                left: '30px',
                right: '10px',
                bottom: '30px',
                containLabel: false
            },
            series: [{
                data: targetData,
                name: '目标',
                type: 'line',
                itemStyle: {
                    normal: {
                        color: '#F4E001'
                    }
                }
            },
            {
                data: actData,
                name: '实际产量',
                type: 'bar',
                itemStyle: {
                    normal: {
                        color: '#F0805A'
                    }
                }
            }]
        };
        return option;
    }
    private getTopOptions(name: string, color: string, category: Array<any>, list: Array<any>): any {

        const option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                    type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                }
            },
            xAxis: {
                type: 'value',
            },
            yAxis: {
                type: 'category',
                data: category
            },
            grid: {
                top: '5px',
                left: '40px',
                right: '10px',
                bottom: '30px',
                containLabel: false
            },
            series: [{
                data: list,
                name: name,
                type: 'bar',
                itemStyle: {
                    normal: {
                        color: color
                    }
                }
            }]
        };
        return option;
    }

}
